<template>
  <div class="container">
    <el-container>
      <el-header>
        <el-row
          type="flex"
          class="row-bg"
          justify="space-between"
          align="middle"
        >
          <el-col :span="3"><div class="grid-content"></div></el-col>
          <el-col :span="12"
            ><div class="grid-content">
              <el-menu
                :default-active="activeIndex"
                class="el-menu-demo"
                mode="horizontal"
                @select="handleSelect"
                background-color="#a0cfff"
                text-color="#fff"
                active-text-color="#409EFF"
              >
                <el-menu-item index="home">首頁</el-menu-item>
                <el-menu-item index="mapList" v-if="isUserInfo()"
                  >导图列表</el-menu-item
                >
                <el-menu-item index="person" v-if="isUserInfo()"
                  >我的信息</el-menu-item
                >
                <el-menu-item index="userMG" v-if="isUserInfo('admin')"
                  >用户管理</el-menu-item
                >
                <el-menu-item index="mapMG" v-if="isUserInfo('admin')"
                  >导图管理</el-menu-item
                >
              </el-menu>
            </div></el-col
          >
          <el-col :span="4">
            <div
              v-if="isUserInfo()"
              class="grid-content userBox"
              @click="loginOut"
            >
              <span class="yellow" v-if="isUserInfo('vip')">VIP</span>
              <img class="user" src="@/assets/user.png" alt="" />
              <span>{{ userInfo.nickName }}</span>

              <el-button
                class="yellow"
                @click.stop="closeVip"
                type="text"
                >{{!isUserInfo('vip')?'成为会员':'充值'}}</el-button
              >
            </div>
            <span v-else @click="onLogin">欢迎登录</span>
          </el-col>
        </el-row>
      </el-header>
      <el-scrollbar style="height: 100%; height: calc(100vh - 60px)">
        <el-main>
          <router-view
            @toLogin="onLogin"
            @updateUser="onUpdateUser"
          ></router-view>
        </el-main>
        <el-footer>
          <div class="grid-content"></div>
          <div class="grid-content">
            某某某某大学·2024·某某专业·某某班级·某某某·毕业设计
          </div>
          <div class="grid-content"></div>
        </el-footer>
      </el-scrollbar>
    </el-container>
    <el-drawer
      title="我嵌套了表格!"
      :visible.sync="table"
      direction="rtl"
      size="50%"
    >
      <el-table :data="gridData">
        <el-table-column
          property="date"
          label="日期"
          width="150"
        ></el-table-column>
        <el-table-column
          property="name"
          label="姓名"
          width="200"
        ></el-table-column>
        <el-table-column property="address" label="地址"></el-table-column>
      </el-table>
    </el-drawer>

    <!-- :before-close="handleClose" -->
    <el-drawer
      :title="isRegister ? '欢迎注册' : '欢迎登录'"
      :visible.sync="showLogin"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="50%"
      :before-close="handleClose"
      @close="cancelLogin"
    >
      <div class="demo-drawer__content">
        <el-form
          class="infoForm"
          :model="formInline"
          ref="infoForm"
          :rules="rules"
        >
          <template v-if="isRegister">
            <el-form-item
              label="用户名"
              prop="nickName"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="formInline.nickName"
                autocomplete="off"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="邮箱"
              prop="email"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="formInline.email"
                autocomplete="off"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="formInline.password"
                autocomplete="off"
                placeholder="只能是数字，字母，特殊字符 8-18位"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="确认密码"
              prop="passwordAgain"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="formInline.passwordAgain"
                autocomplete="off"
                placeholder="只能是数字，字母，特殊字符 8-18位"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="手机号码"
              prop="phone"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="formInline.phone"
                autocomplete="off"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="用户角色"
              prop="role"
              :label-width="formLabelWidth"
            >
              <el-select v-model="formInline.role" placeholder="请选择角色">
                <el-option label="普通用户" value="0"></el-option>
                <el-option label="会员用户" value="2"></el-option>
                <el-option label="管理员" value="1"></el-option>
              </el-select>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input
                v-model="formInline.email"
                autocomplete="off"
                placeholder="请输入用户名或者手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input
                v-model="formInline.password"
                autocomplete="off"
                placeholder="只能是数字，字母，特殊字符 8-18位"
              ></el-input>
            </el-form-item>
          </template>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelLogin">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading">{{
            loading ? "提交中 ..." : isRegister ? "注 册" : "登 录"
          }}</el-button>
        </div>
        <div class="demo-drawer__footer_tip">
          <el-divider content-position="right"
            ><el-button
              class="tipText"
              type="text"
              @click="isRegister = !isRegister"
              >去{{ !isRegister ? "注册" : "登录" }}</el-button
            ></el-divider
          >
        </div>
      </div>
    </el-drawer>
    <el-dialog
  title="成为会员"
  :visible.sync="dialogVisible"
  width="50%"
  :before-close="closeVip">
  <div class="dialogContent">
    <el-radio-group v-model="money" :disabled="QRCode">
    <el-radio :label="10">10元</el-radio>
    <el-radio :label="30">30元</el-radio>
    <el-radio :label="50">50元</el-radio>
  </el-radio-group>
  <img class="QRCode" v-if="QRCode" src="@/assets/user.png" alt="" />
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="closeVip">取 消</el-button>
    <el-button type="primary" @click="onSubmitVip">{{QRCode?'支付完成':'确 定'}}</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { setRoutes } from "../router";
import { setToken, getToken } from "@/utils/auth"; // 引入Cookies
// import { Getlogininformation } from "../api/api";
export default {
  name: "index",
  data() {
    return {
      activeIndex: "home",
      table: false,
      QRCode: false,
      dialogVisible: false,
      showLogin: false,
      isRegister: false,
      loading: false,
      money:10,
      gridData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ],
      formInline: {},
      formLabelWidth: "80px",
      timer: null,
      userInfo: {},
      rules: {
        nickName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        passwordAgain: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 8,
            max: 20,
            message: "长度在 8 到 20 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
        email: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 8,
            max: 20,
            message: "长度在 8 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.onUpdateUser();
  },
  methods: {
    onUpdateUser() {
      if (sessionStorage.getItem("user")) {
        let info = JSON.parse(sessionStorage.getItem("user"));
        this.$set(this, "userInfo", info);
        console.log(this.userInfo);
      }
    },
    isUserInfo(role) {
      if (role && role == "admin" && this.userInfo && this.userInfo.role == 1) {
        return true;
      }
      if (role && role == "vip" && this.userInfo && this.userInfo.role == 2) {
        return true;
      }
      if (this.userInfo && this.userInfo.userId && !role) {
        return true;
      } else return false;
    },
    register() {
      this.$refs["infoForm"].validate((valid) => {
        if (valid) {
          // 表单校验合法
          let obj = this.formInline;
          this.$api.postReqister(obj).then((res) => {
            if (res.code === 200) {
              console.log(res.data);
              sessionStorage.setItem("user", JSON.stringify(obj)); // 存储用户信息到浏览器
              this.$message.success("注册成功");
              this.isRegister = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    login() {
      if (!(this.formInline.email && this.formInline.password)) {
        return this.$message({
          message: "请输入用户名或密码",
          type: "warning",
        });
      } else {
        this.$api.postLogin(this.formInline).then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.$message.success("登录成功");
            // 设置Cookie
            this.$cookies.set("session_key", res.data, 60 * 60 * 24 * 7);
            sessionStorage.setItem("user", JSON.stringify(res.data)); // 存储用户信息到浏览器
            this.$set(this, "userInfo", { ...res.data });
            this.cancelLogin();
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
    handleSelect(val) {
      this.$router.push({
        name: val,
      });
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      if (this.isRegister) {
        this.$confirm("确定结束注册吗？")
          .then((_) => {
            // this.loading = true;
            // this.timer = setTimeout(() => {
            //   done();
            //   // 动画关闭需要一定的时间
            //   setTimeout(() => {
            //     this.loading = false;
            //   }, 400);
            // }, 2000);
          })
          .catch((_) => {});
      } else {
        this.cancelLogin();
      }
    },
    loginOut() {
      this.$confirm("确定退出登录吗？")
        .then((_) => {
          this.userInfo = {};
          this.$api.postLogout().then((res) => {
            if (res.code == 200) {
              // this.activeIndex = "home"
              this.$set(this, "activeIndex", "home");
              sessionStorage.removeItem("user");
              this.$router.push({
                name: "home",
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch((_) => {});
    },
    onSubmitVip() {
      if (this.QRCode) {
        // 支付
        console.log("onSubmitVip",this.money);
        let data = {
          price:this.money,
          id:this.userInfo.userId
        }
        this.$api.submitVip(data).then((res) => {
            if (res.code == 200) {
              this.closeVip()
              this.getInfo()
              this.$message.success('充值成功');
            } else {
              this.$message.error(res.msg);
            }
          });
      } else {
        this.QRCode = true
      }
    },
    closeVip(){
      this.money = 10
      this.QRCode = false
      this.dialogVisible = !this.dialogVisible
    },
    onLogin() {
      this.loading = false;
      this.showLogin = true;
      this.isRegister = false;
    },
    cancelLogin() {
      this.formInline = {};
      this.loading = !this.loading;
      this.showLogin = false;
      this.isRegister = false;
      clearTimeout(this.timer);
    },
    onSubmit() {
      // $refs.drawer.closeDrawer()
      if (this.isRegister) {
        // 注册
        this.register();
      } else {
        // 登录
        this.login();
      }
    },
    getInfo() {
      this.$api.getUserInfo().then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.userInfo = res.data;
          // 设置Cookie
              this.$cookies.set('session_key', res.data, 60*60*24*7);
              sessionStorage.setItem("user", JSON.stringify(res.data)); // 存储用户信息到浏览器
          // this.form = {};
          this.onUpdateUser()
        } else {
          this.$message.error(res.msg);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialogContent {
      display: flex;
    justify-content: center;
    flex-flow: column;
    align-items: center;
  .QRCode {
        width: 300px;
    height: 300px;
    margin: 10px;
  }
}
.yellow {
  color: #e6a23c;
}
.container {
  height: 100vh;
  /* background-image: -webkit-gradient(linear, left top, right bottom, from(#FC466B), to(#3F5EFB)); */
  background-image: linear-gradient(to bottom right, #ffffff, #2e92fa);
  overflow: hidden;
}
.el-header {
  background: #409eff;
  .row-bg {
    height: 60px;
  }
  .userBox {
    display: inline-flex;
    align-items: center;
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 5px;
    }
  }
}
::v-deep .el-scrollbar__wrap {
  overflow-x: auto !important;
}
.el-main {
  min-height: 85vh;
  background: #ffffff;
  padding: 0px;
  //     display: flex;
  // justify-content: center;
  // align-items: center;
  .adMain {
  }
  .el-carousel__item {
    background: #409eff;
  }
}
.el-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  .grid-content {
  }
}
.demo-drawer__content {
  .infoForm {
    padding: 20px 40px 20px 20px;
  }
  .demo-drawer__footer {
  }
  .demo-drawer__footer_tip {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 20px 0 70px;
    // border-top: 2px solid #409EFF;
    .tipText {
      font-size: 24px;
    }
  }
}
</style>
